package pac

import (
	"encoding/json"
	db "slgw_web/application/gormdb"
	"slgw_web/serial/util"
	"time"

	models "openzbox.com/frame/echo/models/sl_gw01"
)

//四表集中器协议

type P struct {
	Func string                 `json:"Func"`
	Dev  string                 `json:"Dev"`
	Data map[string]interface{} `json:"Data"`
}

func TaskReportedConcentratorData(sb models.DeviceInfo) {
	var collectDataList = util.CollectDataList        //采集到的信息
	var deviceDetailList = util.DeviceInfo_DetailList //对应的上报点位
	var deviceConcentrator = util.DeviceInfo_Concentrator
	var deviceConcentratorUser = util.DeviceInfo_Concentrator_User
	now := time.Now().Format("2006-01-02 15:04:05")
	if len(collectDataList) > 0 && len(deviceDetailList) > 0 && len(deviceConcentrator) > 0 && len(deviceConcentratorUser) > 0 {
		for _, C := range deviceConcentrator { //集中器
			if C.Device_ID == sb.ID {
				errStr := sb.Name + ",dev:" + C.Dev
				for _, CU := range deviceConcentratorUser { //用户表
					if CU.Device_ID == sb.ID && CU.DeviceInfo_Concentrator_ID == C.ID {
						params1 := make(map[string]interface{})
						params2 := make(map[string]interface{})
						params3 := make(map[string]interface{})
						for _, DD := range deviceDetailList { //对应的上报点位
							if DD.DeviceInfo_Concentrator_ID != nil && DD.DeviceInfo_Concentrator_User_ID != nil {
								if *DD.DeviceInfo_Concentrator_ID == C.ID && *DD.DeviceInfo_Concentrator_User_ID == CU.ID && DD.Device_ID == sb.ID {
									{
										for _, CD := range collectDataList {
											if CD.Value2 == nil {
												*CD.Value2 = ""
											}
											if CD.ID == DD.Serial_Slave_Detail_ID { //如果采集到的是需要上报的点位
												if *DD.ConcentratorType == 1 { //水表
													params1[DD.ConcentratorKey] = *CD.Value2
												} else if *DD.ConcentratorType == 2 { //电表
													params2[DD.ConcentratorKey] = *CD.Value2
												} else if *DD.ConcentratorType == 3 { //流量计
													params3[DD.ConcentratorKey] = *CD.Value2
												}
											}
										}
									}
								}
							}
						}

						if len(params1) > 0 {
							params1["DT"] = now
							params1["Mn"] = CU.Mn
							paramss := make([]map[string]interface{}, 0)
							paramss = append(paramss, params1)
							paramAll := make(map[string]interface{})
							paramAll["Type"] = "01"
							paramAll["Data"] = paramss
							params := util.Concentrator_SendData{Func: 3, Dev: C.Dev, Data: paramAll}
							//fmt.Println("params1", params)
							SendConcentratorData(params, errStr, sb, now)
						}
						if len(params2) > 0 {
							params2["DT"] = now
							params2["Mn"] = CU.Mn
							paramss := make([]map[string]interface{}, 0)
							paramss = append(paramss, params2)
							paramAll := make(map[string]interface{})
							paramAll["Type"] = "01"
							paramAll["Data"] = paramss
							params := util.Concentrator_SendData{Func: 3, Dev: C.Dev, Data: paramAll}
							SendConcentratorData(params, errStr, sb, now)
							//fmt.Println("params2", params)
						}
						if len(params3) > 0 {
							params3["DT"] = now
							params3["Mn"] = CU.Mn
							paramss := make([]map[string]interface{}, 0)
							paramss = append(paramss, params3)
							paramAll := make(map[string]interface{})
							paramAll["Type"] = "01"
							paramAll["Data"] = paramss
							params := util.Concentrator_SendData{Func: 3, Dev: C.Dev, Data: paramAll}
							SendConcentratorData(params, errStr, sb, now)
							//fmt.Println("params3", params)
						}
					}
				}
			}
		}
	}
}

// 发送上报数据
func SendConcentratorData(params util.Concentrator_SendData, errStr string, sb models.DeviceInfo, now string) {

	jsonData, err := json.Marshal(params)
	if err != nil {
		util.Error(errStr + " 发送数据包失败 ,Error encoding JSON:" + err.Error())
	} else {
		//fmt.Print("aaa", string(jsonData))
		//如果开启断点重传功能，就把历史记录保存，并且每次发送前判断是否有需要续传的数据记录
		if util.IsRereported == 1 {
			db := db.GetDB()
			if len(util.RereportedTag) > 0 { //判断是否需要查询数据库续传
				RereportedDay := -1
				RI := 0
				//fmt.Println("util.RereportedTag1", util.RereportedTag)
				for RId, RItem := range util.RereportedTag {
					if RItem.DeviceInfo_ID == sb.ID {
						RereportedDay = RItem.RereportedDay
						RI = RId
						break
					}
				}
				//fmt.Println("RereportedDay1", RereportedDay)
				if RereportedDay != -1 {
					if RereportedDay != time.Now().Day() { //如果上次续传的日期是今天，就不再续传 等待下次
						//go func() {
						util.RereportedTag[RI].RereportedDay = time.Now().Day()
						time.Sleep(1 * time.Second) //延时 防止粘包
						var collectDataList []models.CollectData
						db.Where("Device_ID = ? ", sb.ID).Find(&collectDataList)
						if len(collectDataList) > 0 {
							//把上传失败的重新上传
							for _, item := range collectDataList {
								SendDataByte([]byte(item.Data), sb)
								time.Sleep(1 * time.Second)
							}
						}
						//}()
						// //删除3天前的数据
						k := time.Now()
						d, _ := time.ParseDuration("-24h")
						s := k.Add(3 * d).Format("2006-01-02 00:00:00")
						result := db.Where("CreateTime<=?", s).Delete(&models.CollectData{})
						rows := result.RowsAffected //删除的条数
						if rows > 0 {
							db.Exec("VACUUM") //释放空闲的占用
						}
					}
				}
				//fmt.Println("util.RereportedTag2", util.RereportedTag)
			}
			CollectDatas := models.CollectData{
				Device_ID:       sb.ID,
				DeviceInfoID:    sb.DeviceInfoID,
				Data:            string(jsonData),
				CreateTime:      now,
				ConcentratorDev: params.Dev,
			}
			db.Create(&CollectDatas)

		}
		SendDataByte(jsonData, sb)
	}
}
